//
//  CameraTakeMamanger.m
//  yilingdoctorCRM
//
//  Created by 陈腾飞 on 14/10/31.
//  Copyright (c) 2014年 yuntai. All rights reserved.
//

#import "CameraTakeMamanger.h"
#import "UIImage+Camera.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "AuthorityManager.h"


#define IS_IOS_8_OR_LATER [[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0

#import <MobileCoreServices/MobileCoreServices.h>

@interface CameraTakeMamanger()<UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate>

@property(nonatomic, weak) UIViewController *vc;
@property(nonatomic, strong) UIImagePickerController *imagePickerController;
@property(nonatomic, copy) void (^resultBlock)(UIImage *image ,NSString * imagePath);
@property(nonatomic, copy) void (^cancelBlock)(void);
@property(nonatomic, copy) void (^resultVideoBlock)(NSURL *videoUrl);

@property (nonatomic, assign) BOOL isIM;
@end

@implementation CameraTakeMamanger

static CameraTakeMamanger *sharedInstance = nil;
#pragma mark Singleton Model
+ (CameraTakeMamanger *)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[CameraTakeMamanger alloc]init];
        sharedInstance.isIM = NO;
        if (IS_IOS_8_OR_LATER) {
//            sharedInstance.imagePickerController.modalPresentationStyle = UIModalPresentationOverFullScreen;
        }
        
        
        [[NSNotificationCenter defaultCenter]addObserver:sharedInstance
                                                selector:@selector(imagePickerViewDissNotification)
                                                    name:kOneSelectPhotoAlbumVCDismissNotification
                                                  object:nil];
        
        
        
    });
    return sharedInstance;
}

- (void)initImageVC{
    if(self.imagePickerController == nil){
        self.imagePickerController = [[UIImagePickerController alloc]init];
        self.imagePickerController.delegate = self;
        self.imagePickerController.navigationBar.translucent = NO;
        self.imagePickerController.allowsEditing = YES;
    }
}
/**
 *  页面dissmiss的通知
 */
- (void)imagePickerViewDissNotification
{
    if (self.vc) {
        [self.imagePickerController dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
    
}
#pragma mark - public methods
- (void)cameraSheetInController:(UIViewController *)vc
                        handler:(void (^)(UIImage *image ,NSString * imagePath))block
                  cancelHandler:(void (^)(void))cancelBlock{
    self.vc = vc;
    self.resultBlock = block;
    self.cancelBlock = cancelBlock;
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:@"拍照",@"从相册选择", nil];
    
    sheet.actionSheetStyle = UIActionSheetStyleAutomatic;

    [sheet showInView:self.vc.view];
}

- (void)mediWithCameraInController:(UIViewController *)vc
                           handler:(void (^)(UIImage *image ,NSString * mediaPath))block
                     cancelHandler:(void (^)(void))cancelBlock
{
    self.vc = vc;
    self.resultBlock = block;
    self.cancelBlock = cancelBlock;
    
    self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.imagePickerController.mediaTypes = @[(NSString *)kUTTypeMovie];
    self.imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.vc presentViewController:self.imagePickerController animated:YES completion:^{}];
    });
}
- (void)imageWithCameraInController:(UIViewController *)vc
                            handler:(void (^)(UIImage *image ,NSString * imagePath))block
                      cancelHandler:(void (^)(void))cancelBlock
                               isIM:(BOOL)isIM {
    self.vc = vc;
    self.resultBlock = block;
    self.cancelBlock = cancelBlock;
    self.isIM = isIM;
    
    __weak typeof(self) weakself = self;
    [[AuthorityManager sharedInstance] judgeCaramerStatus:^(BOOL status) {
        if (status) {
            [weakself initImageVC];
            weakself.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            weakself.imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakself.vc presentViewController:weakself.imagePickerController animated:YES completion:nil];
            });
        }else{
            
        }
    }];
}

- (void)imageWithPhotoInController:(UIViewController *)vc
                           handler:(void (^)(UIImage *image ,NSString * imagePath))block
                     cancelHandler:(void (^)(void))cancelBlock;{
    self.vc = vc;
    self.resultBlock = block;
    self.cancelBlock = cancelBlock;
    
    // 跳转到相册页面
    if ([[AuthorityManager sharedInstance]judgePhotoStatus]) {
        __weak typeof(self) weakself = self;
        
        [weakself initImageVC];
        
        weakself.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakself.vc presentViewController:weakself.imagePickerController animated:YES completion:^{}];
        });
    }
}

#pragma mark - UIImagePickerControllerDelegate



- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    
    self.imagePickerController = nil;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    self.imagePickerController = nil;
    //获取媒体类型
    NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    if (![mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        // 摄像
        NSURL *videoUrl = [info objectForKey:UIImagePickerControllerMediaURL];
        self.resultVideoBlock(videoUrl);
        
    } else {
        // 照片
        [picker dismissViewControllerAnimated:YES completion:^{}];
        UIImage *image = [info objectForKey:self.isCanEdit ? UIImagePickerControllerEditedImage :UIImagePickerControllerOriginalImage];
        NSString *imageName = [NSString stringWithFormat:@"%@.png",[NSUUID UUID].UUIDString];
        //        [self saveImage:image withName:imageName];
        //        NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
        //        UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
        self.resultBlock(image,imageName);
    }
    
};

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    self.imagePickerController = nil;
    [self.vc dismissViewControllerAnimated:YES completion:^{
        if(self.cancelBlock)
        {
            self.cancelBlock();
        }
        
    }];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 0) {
        // 跳转到相机
        __weak typeof(self) weakself = self;
        [[AuthorityManager sharedInstance] judgeCaramerStatus:^(BOOL status) {
            if (status) {
                [weakself initImageVC];
                weakself.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                weakself.imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakself.vc presentViewController:weakself.imagePickerController animated:YES completion:nil];
                });
            }else{
                
            }
        }];
        
        //        if([[AuthorityManager sharedInstance]judgeCaramerStatus]){
        //            self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        //            self.imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        //            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //                [self.vc presentViewController:self.imagePickerController animated:YES completion:^{}];
        //            });
        //        }
        
    }
    
    if (buttonIndex == 1) {
        // 跳转到相册页面
        if ([[AuthorityManager sharedInstance]judgePhotoStatus]) {
            __weak typeof(self) weakself = self;

            [weakself initImageVC];

            weakself.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakself.vc presentViewController:weakself.imagePickerController animated:YES completion:^{}];
            });
        }
        
    }
    
    if (buttonIndex == 2) {
        // 取消
        __weak typeof(self) weakself = self;
        [weakself.vc dismissViewControllerAnimated:YES completion:^{
            weakself.cancelBlock();
        }];
    }
}

#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    
    
    NSData *temp = UIImageJPEGRepresentation(currentImage, 1);
    
    CGFloat tempSize = [temp length] / 1024;
    // 规定大小
    CGFloat theSize = 200.0;
    // 大于200kb 就压缩
    CGFloat ratio;
    if (tempSize > theSize) {
        ratio = (theSize / tempSize) * 2.5;
    } else {
        ratio = 1;
    }
    
    if(self.isIM){
        
        //     NSString *filePath =   [SaveImageUtils saveChatImage:[currentImage fixOrientation:currentImage] withName:imageName];
        //        self.resultBlock([currentImage fixOrientation:currentImage],filePath);
        
    }else{
        
        temp = UIImageJPEGRepresentation([currentImage fixOrientation:currentImage], ratio);
        // 获取沙盒目录
        NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
        // 将图片写入文件
        [temp writeToFile:fullPath atomically:YES];
        self.resultBlock([currentImage fixOrientation:currentImage],fullPath);
        
    }
    
    
    
}


@end

